package com.ld.businessCard.action;

import com.ld.businessCard.entity.User;
import com.ld.businessCard.service.UserService;
import com.ld.businessCard.service.impl.UserServiceImpl;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class UserAction implements ModelDriven<User> {
	private User user;
	private UserService userService = new UserServiceImpl();
	public User getModel() {
		user = new User();
		return user;
	}
	public String login(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		if(user.getPassword() == null){
			session.setAttribute("error","密码为空");
			return "login-fail";
		}else if(user.getAccount() == null){
			session.setAttribute("error","账号为空");
			return "login-fail";
		}
		System.out.println(user);
		User user1 = userService.login(user.getAccount(),user.getPassword());
		if(user1 == null ){
			session.setAttribute("error","账号或者密码错误");
			return "login-fail";
		}else {
			session.setAttribute("user",user1);
			if(user1.getStatus() == 0){
				return "login-user";
			}else {
				return "login-admin";
			}
		}


	}
	public String register(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		if(user.getPassword() == null){
			request.setAttribute("error","密码为空");
			return "register-fail";
		}else if(user.getAccount() == null){
			request.setAttribute("error","账号为空");
			return "register-fail";
		}else if(user.getUsername() == null){
			request.setAttribute("error","用户名为空");
			return "register-fail";
		}
		user.setStatus(0);
		int register = userService.register(user);
		if(register == 0 ){
			session.setAttribute("error","注册失败");
			return "register-fail";
		}else {
			return login();
		}


	}
	public String deleteUser(){
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		int i = userService.deleteUserById(user.getId());
		if(i == 1){
			session.setAttribute("message","删除成功");
		}else {
			session.setAttribute("message","删除失败");
		}
		return "user-delete";


	}

}
